import { Suspense, useEffect, useState } from "react";
import { Environment, OrbitControls, PerspectiveCamera } from "@react-three/drei";
import Ground from "./Ground.jsx";
import Track from "./Track.jsx";
import Car from "./Car.jsx";

const Scene = () => {
  const [thirdPerson, setThirdPerson] = useState(false);
  const [cameraPosition, setCameraPosition] = useState([-6, 3.9, 6.21]);

  useEffect(() => {
    function keyDownHandler(e) {
      if (e.key === "k") {
        if (thirdPerson) setCameraPosition([-6, 3.9, 6.21 + Math.random() * 0.01]);
        setThirdPerson(!thirdPerson);
      }
    }

    window.addEventListener("keydown", keyDownHandler);
    return () => {
      window.removeEventListener("keyup", keyDownHandler);
    };
  }, [thirdPerson]);

  return (
    <Suspense fallback={null}>
      <Environment files="./textures/envmap.hdr" background={true} />
      <PerspectiveCamera makeDefault position={cameraPosition} fov={40} />
      {!thirdPerson && (
        <OrbitControls target={[-2.64, -0.71, 0.03]} />
      )}
      <Track />
      <Ground />
      <Car thirdPerson={thirdPerson} />
    </Suspense>
  );
};

export default Scene;